<?php

namespace Georgie\PhpRbac\model;

use think\facade\Db;

class Base
{
    protected $tableName = "";
    protected $data_ = [];


    /**
     * 返回相关DB类
     * @return Db
     * @author Georgie 227040015@qq.com
     */
    public function db()
    {
        return Db::name($this->tableName);
    }

    /**
     * 设置data数据
     * @param $data array 设置的数据
     * @return $this
     * @author Georgie 227040015@qq.com
     */
    public function data($data = [])
    {
        $this->data_ = $data;
        return $this;
    }

    /**
     * 插入数据
     * @param $data array 创建的数据
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function create($data = [])
    {
        return $this->db()->insert($data ?? $this->data_);
    }

    /**
     * 修改数据
     * @param $data array 修改的数据 需传入id
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function edit($data = [])
    {
        if (!empty($data))
            $this->data($data);

        if (!$this->data_['id'])
            throw new \Exception('请传入ID');

        return $this->db()->where('id', $this->data_['id'])->update($this->data_);
    }

    /**
     * 修改数据
     * @param $id int 删除的id
     * @return bool
     * @author Georgie 227040015@qq.com
     */
    public function del($id = 0)
    {
        $this->data(['id' => $id ?? ($this->data_['id'] ?? 0)]);
        if (!$this->data_['id']) throw new \Exception('请传入ID');

        $this->db()->where('id', $this->data_['id'])->delete();

        return true;
    }

    /**
     * 修改数据
     * @param $condition array 筛选条件，带id时是对象，不带id是数组
     * @return array
     * @author Georgie 227040015@qq.com
     */
    public function get(array $condition = [])
    {
        $orm = $this->db()->where($condition);

        if (isset($condition['id']))
            return $orm->find();
        else
            return $orm->select();
    }
}